<?php
/**
 * Created by PhpStorm.
 * User: Vlad
 * Date: 2/8/14
 * Time: 10:08 AM
 */

class Loader
{
    private $controller;
    private $action;
    private $urlValues;

    //store the URL values on object creation

    public function __construct($urlValues)
    {
        $this->urlValues = $urlValues;
        if ($this->urlValues['controller'] == "")
        {
            $this->controller = "HomeController";
        }
        else
        {
            $this->controller = ucfirst($this->urlValues['controller']) . 'Controller';
        }
        if ($this->urlValues['action'] == "")
        {
            $this->action = "Index";
        }
        else
        {
            $this->action = ucfirst($this->urlValues['action']);
        }
    }

    //establish the requested controller as an object
    public function CreateController()
    {
        //does the class exist?
        if (class_exists($this->controller))
        {
            $parents = class_parents($this->controller);
            //does the class extend the controller class?
            if (in_array("BaseController", $parents))
            {
                //does the class contain the requested method?
                if (method_exists($this->controller, $this->action))
                {
                    return new $this->controller($this->action, $this->urlValues);
                }
            }
        }

        /// TODO: return an error
        return null;
    }
} 